#-*-coding:utf-8-*-

import os
from hashlib import sha1
from hashlib import md5
from config import upload_dir
def _mkdir(newdir):
    """works the way a good mkdir should :)
        - already exists, silently complete
        - regular file in the way, raise an exception
        - parent directory(ies) does not exist, make them as well
    """
    if os.path.isdir(newdir):
        pass
    elif os.path.isfile(newdir):
        raise OSError("a file with the same name as the desired " \
                      "dir, '%s', already exists." % newdir)
    else:
        head, tail = os.path.split(newdir)
        if head and not os.path.isdir(head):
            _mkdir(head)
        #print "_mkdir %s" % repr(newdir)
        if tail:
            os.mkdir(newdir)

def hash_password(password):
    return str(sha1(password + 'yerp').hexdigest()) 
    
def checksum(data):
    return str(md5(data).hexdigest())

def coderule(rule):
    '''解析编码规则如3-3-3-3-3 解析成[3,6,9,12,15]'''
    def q(string):
        total=0
        for num in string.split('-'):
            total +=int(num)
            yield total
    return list(q(rule))
class AppStatus(object):
    """
    返回状态    
    """
    @classmethod
    def ok(cls):
        return '{"statusCode":"200","message":"操作已成功"}' 
    @classmethod
    def ok_msg(cls,msg):
        return '{"statusCode":"200","message":"%s"}' %msg
    @classmethod
    def ok_forward(cls,navTabId):
        return '{"statusCode":"200","message":"操作已成功","callbackType":"forward","navTabId":"%s"}' %navTabId
    @classmethod
    def ok_closeCurrent(cls):
        return '{"statusCode":"200","callbackType":"closeCurrent","message":"操作已成功"}'
    @classmethod
    def failure(cls,message):
        return '{"statusCode":"300","message":"操作失败,%s"}' %message
    @classmethod
    def failureSession(cls):
        return '{"statusCode":"301","message":"超时，请重新登陆"}' 
def uploadfile(filename,file,path=''):
    fout = open(upload_dir+path +'/'+ filename,'wb')
    fout.write(file.read())
    fout.close()
    
if __name__ == "__main__":
    print AppStatus.ok()
    print AppStatus.ok_forward('zhaoyh')
    print AppStatus.ok_closeCurrent()
    print AppStatus.failure('failure')
    print AppStatus.failureSession()
    print coderule('2-3-6-5-1-5')
    print hash_password('zhaoyh')
    print checksum('zhaoyh')
